import { GetSysDict_API } from '@/server/home'
import { defineStore } from 'pinia'

/**
 * 字典数据存储
 */
export const useDictStore = defineStore('dict', {
    state: () => ({
        // 字典数据缓存
        dictData: <any>{},
    }),
    actions: {
        /**
         * 获取字典数据
         * @param dicts 字典类型数组
         */
        async getDictData(dicts: string[]) {
            // 并行请求所有字典数据
            const promises = dicts.map(async (dict) => {
                // 如果字典数据不存在或为空，则请求数据
                if (!this.dictData[dict] || this.dictData[dict].length === 0) {
                    const res = await GetSysDict_API(dict)
                    if (res.IsSuccess && res.Data.length > 0) {
                        // 格式化字典数据
                        this.dictData[dict] = res.Data.map((item) => ({
                            text: item.Label,
                            value: item.Value,
                        }))
                    } else {
                        this.dictData[dict] = []
                    }
                }
            })
            // 等待所有请求完成
            await Promise.all(promises)
            return this.dictData
        },
    },
    persist: {
        storage: {
            getItem(key) {
                return uni.getStorageSync(key)
            },
            setItem(key, value) {
                uni.setStorageSync(key, value)
            },
        },
    },
})
